using System.Collections.Generic;
using Bases;
using Configs;
using Modules.Game.Skills;
using UnityEngine;

namespace Modules.Tip
{
    public class TipPanel : MonoBehaviourSimplify
    {
        public GameObject skillDescItemPrefab;

        public GameObject tipItemPrefab;

        public GameObject tipGroup;

        private readonly List<GameObject> _items = new();

        private GameObject _descItem;

        private void Awake()
        {
            RegisterMsg(EventConfig.OpenSkillDescTip, OnSkillDescTip);
            RegisterMsg(EventConfig.OpenTip, OnTip);
        }

        protected override void OnBeforeDestroy()
        {
        }

        private void OnSkillDescTip(object skillDescData)
        {
            if (skillDescData == null)
            {
                if (!_descItem || !_descItem.activeSelf) return;

                if (_descItem.GetComponent<SkillDescItem>().isSelect) return;

                Destroy(_descItem);
                _descItem = null;

                return;
            }

            if (_descItem && _descItem.activeSelf)
            {
                _descItem.GetComponent<SkillDescItem>().UpdateDescData((SkillDescData) skillDescData);
                return;
            }

            _descItem = Instantiate(skillDescItemPrefab, transform);
            _descItem.GetComponent<SkillDescItem>().UpdateDescData((SkillDescData) skillDescData);
        }

        private void OnTip(object text)
        {
            _items.ForEach(item =>
            {
                var pos = item.GetComponent<RectTransform>().localPosition;
                pos.y += item.GetComponent<RectTransform>().sizeDelta.y;
                item.GetComponent<RectTransform>().localPosition = pos;
            });

            var tipItem = Instantiate(tipItemPrefab, tipGroup.transform);
            tipItem.GetComponent<TipItem>().OnTip(text.ToString());
            _items.Add(tipItem);

            Delay(1.0f, () =>
            {
                Destroy(tipItem);
                _items.Remove(tipItem);
            });
        }
    }
}